/*
 * @LastEditors: 七七
 * @Date: 2023-01-06 10:24:54
 */
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import './List.css'

export default class List extends Component {

  //初始化状态
  state = {
    users: [], //users初始值为数组
    isFirst: true, //是否为第一次打开页面
    isLoding: false, //是否处于加载状态
    err: '', //存储请求相关的错误信息
  }

  //订阅消息
  componentDidMount() {
    // 订阅消息
    // 下划线_占位，订阅消息函数两个参数(msg,data)
    this.token = PubSub.subscribe('atguigu', (_, stateObj) => {
      this.setState(stateObj)
    })
  }

  //取消订阅
  componentWillUnmount() {
    PubSub.unsubscribe(this.token);
  }


  render() {
    const { users, isFirst, isLoding, err } = this.state
    return (
      <div className="row">
        {
          isFirst ? <h2>欢迎使用，输入关键字，随后点击搜索</h2> :
            isLoding ? <h2>Loding...</h2> :
              err ? <h2 style={{ color: 'red' }}>{err}</h2> :
                users.map(userObj => {
                  return (
                    <div key={userObj.id} className="card">
                      <a href={userObj.html_url} target="_blank" rel='noreferrer'>
                        <img src={userObj.avatar_url} style={{ width: '100px' }} alt="head_portrait" />
                      </a>
                      <p className="card-text">reactjs</p>
                    </div>
                  )
                })
        }
      </div>
    )
  }
}
